package common.config.mvc;

import com.alibaba.cloud.seata.web.SeataHandlerInterceptor;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import common.util.Constants;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * mvc配置
 *
 * @author 米泽鹏
 * @since 2021-08-05 6:02 下午
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

	@Value("${spring.application.name}")
	private String appName;

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
		FastJsonConfig config = new FastJsonConfig();
		config.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		config.setCharset(StandardCharsets.UTF_8);
		// 关闭循环引用检测，设置允许返回为null的属性
		config.setSerializerFeatures(Constants.SERIALIZER_FEATURES);
		// 解决乱码的问题
		fastJsonConverter.setSupportedMediaTypes(Constants.SUPPORTED_MEDIA_TYPES);
		fastJsonConverter.setFastJsonConfig(config);
		converters.add(fastJsonConverter);
		super.addDefaultHttpMessageConverters(converters);
	}

	/**
	 * knife4j静态资源
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
	}

	/**
	 * knife4j
	 */
	@Override
	public void addViewControllers(@NotNull ViewControllerRegistry registry) {
		if (!Constants.SERVICE_NAME_GATEWAY.equals(appName)) {
			registry.addViewController("/" + appName + "/v2/api-docs").setViewName("forward:/v2/api-docs");
		}
	}

	/**
	 * 解决服务之间无法接收到seata全局事务id
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new SeataHandlerInterceptor()).addPathPatterns("/**");
	}

}
